package com.peitamerchants.Common;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.igexin.sdk.PushManager;
import com.peitamerchants.api.CommonApi;
import com.peitamerchants.application.MainApplication;
import com.peitamerchants.ui.chat.ConversationListActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import io.rong.imkit.MainActivity;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;

/**
 * Created by zy on 2017/5/12.
 */

public class CommonModule extends ReactContextBaseJavaModule {
    private ReactApplicationContext reactContext;
    private final String MODULE_NAME = "CommonModule";
    public CommonModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }
    @Override
    public String getName() {
        return MODULE_NAME;
    }
    @ReactMethod
    public void getCid(Callback callback){
        String cid = PushManager.getInstance().getClientid(reactContext);
        callback.invoke(callback);
    }

    // 获取融云的token
    @ReactMethod
    public void getRongToken(String userToken, final String userId, final String userName, final String userIcon) {

        MainApplication.setToken(userToken);
        OkHttpUtils
                .get()
                .url(CommonApi.RONGIM_TOKEN+"?access-token="+userToken)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println("融云获取失败："+e.getMessage());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("融云获取成功:"+response);
                        if(response != null && response.indexOf("token") != 1){
                            String[] str = response.split(":");
                            String string = str[str.length - 1];
                            int endIndex = string.lastIndexOf("\\");
                            string = string.substring(2, endIndex);
                            RongIM.getInstance()
                                    .refreshUserInfoCache(new UserInfo(userId, userName, Uri.parse(CommonApi.USER_ICON+userIcon)));
                            connect(string);
                        }
                    }
                });
    }
    /**
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     * @param token    从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token) {
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    // 重新获取token

                }
                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    System.out.println("连接成功:"+userid);

                }
                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
    }
    /**
     * RN调用Native的方法
     */
    @ReactMethod
    public void openActivity(String string) {
        if(TextUtils.isEmpty(string)){
            return ;
        }
        Intent intent = null;
        if( "ConversationListActivity".equals(string)){
            intent = new Intent(reactContext, ConversationListActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if(intent != null){
            reactContext.startActivity(intent);
        }
    }

    /**
     *
     * @param isPrivate true 单聊
     * @param id
     * @param name
     */
    @ReactMethod
    public void startChat(boolean isPrivate, String id, String name){
        if(TextUtils.isEmpty(id)){
            return;
        }
        if(isPrivate){
            if(reactContext != null && !TextUtils.isEmpty(id)) {
                if(RongContext.getInstance() == null) {
                    throw new ExceptionInInitializerError("RongCloud SDK not init");
                } else {
                    Uri uri = Uri.parse("rong://" + reactContext.getApplicationInfo().packageName)
                            .buildUpon().appendPath("conversation")
                            .appendPath(Conversation.ConversationType.PRIVATE.getName().toLowerCase())
                            .appendQueryParameter("targetId", id)
                            .appendQueryParameter("title", name)
                            .build();

                    Intent intent = new Intent("android.intent.action.VIEW", uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    reactContext.startActivity(intent);
                }
            } else {
                throw new IllegalArgumentException();
            }

        }else{

            if(reactContext != null && !TextUtils.isEmpty(id)) {
                if(RongContext.getInstance() == null) {
                    throw new ExceptionInInitializerError("RongCloud SDK not init");
                } else {
                    Uri uri = Uri.parse("rong://" + reactContext.getApplicationInfo().packageName)
                            .buildUpon().appendPath("conversation")
                            .appendPath(Conversation.ConversationType.GROUP.getName().toLowerCase())
                            .appendQueryParameter("targetId", id)
                            .appendQueryParameter("title", name).build();
                    Intent intent = new Intent("android.intent.action.VIEW", uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    reactContext.startActivity(intent);
                }
            } else {
                throw new IllegalArgumentException();
            }
        }
    }

    /**
     * 调用Rn的方法
     * @param id
     */
    public void nativeCallRn(String id){
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("id",id);
    }

}
